package com.apinji.alipay;

import com.apinji.alipay.dto.AlipayRefundDto;
import com.apinji.alipay.dto.AlipayRefundQueryDto;
import com.apinji.alipay.service.AlipayRefundService;
import com.apinji.common.domain.wrapper.Reply;
import com.apinji.common.plugin.Mutual;
import com.apinji.common.plugin.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Pattern;

/**
 * 支付宝网站支付，退款
 *
 */
@RestController
@EnableAutoConfiguration
@EnableAsync
@RequestMapping("/v1.0/alipay")
public class AlipayRefundController {
    @Autowired
    private AlipayRefundService alipayRefundService;

    /**
     * 支付宝网站退款
     *
     * @param alipayRefundDto
     * @return
     */
    @RequestMapping(value = "/refund")
    public Reply refund(@RequestBody AlipayRefundDto alipayRefundDto) throws Exception{
        if(StrUtils.isEmpty(alipayRefundDto.getUserUUID())) {
            return Mutual.invalidParamAppend("userUUID");
        }
        if(StrUtils.isEmpty(alipayRefundDto.getOrderId())) {
            return Mutual.invalidParamAppend("orderId");
        }
        if(StrUtils.isEmpty(alipayRefundDto.getConsumeOutOrderId())) {
            return Mutual.invalidParamAppend("consumeOutOrderId");
        }
        if(StrUtils.isEmpty(alipayRefundDto.getRefundOutOderId())) {
            return Mutual.invalidParamAppend("refundOutOderId");
        }
        if(!Pattern.matches("^[0-9a-zA-Z]{4,40}", alipayRefundDto.getRefundOutOderId())) {
            return Mutual.invalidParam("[refundOutOderId]参数不合法");
        }
        if(alipayRefundDto.getTxnAmt() <= 0) {
            return Mutual.invalidParam("退款金额不能少于0");
        }
        //
        return alipayRefundService.refund(alipayRefundDto);
    }


    /**
     * 支付宝退款状态查询
     * @param alipayRefundQueryDto
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/refundQuery")
    public Reply refundQuery(@RequestBody AlipayRefundQueryDto alipayRefundQueryDto) throws Exception{
        if(StrUtils.isEmpty(alipayRefundQueryDto.getUserUUID())) {
            return Mutual.invalidParamAppend("userUUID");
        }
        if(StrUtils.isEmpty(alipayRefundQueryDto.getId())) {
            return Mutual.invalidParamAppend("id");
        }
        //
        return alipayRefundService.refundQuery(alipayRefundQueryDto);
    }


}
